package be.jaisy.adapter.hibernate.manager;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;



public class SessionFactoryManager {

	private static SessionFactoryManager INSTANCE;
	
	private Map<String, SessionFactoryWrapper> sessionFactories;
	
	private SessionFactoryManager() {
		super();	
		this.sessionFactories = new HashMap<String, SessionFactoryWrapper>();
	}

	public static SessionFactoryManager getInstance(){
		if(INSTANCE == null)
			INSTANCE = new SessionFactoryManager();
		return INSTANCE;
	}
	
	public SessionFactory getSessionFactory(String sessionFactoryId){
		SessionFactoryWrapper sessionFactoryWrapper = this.sessionFactories.get(sessionFactoryId);
		if(sessionFactoryWrapper==null)
			throw new IllegalArgumentException("Cannot get SessionFactory, SessionFactory with id ["+sessionFactoryId+"] not registered");
		return sessionFactoryWrapper.getSessionFactory();
	}
	
	public void addSessionFactory(String sessionFactoryId, URL configurationPath){
		SessionFactoryWrapper sessionFactoryWrapper = this.sessionFactories.get(sessionFactoryId);
		if(sessionFactoryWrapper == null){
			sessionFactoryWrapper = new SessionFactoryWrapper(sessionFactoryId);
			this.sessionFactories.put(sessionFactoryId, sessionFactoryWrapper);
		}
		sessionFactoryWrapper.setConfigurationPath(configurationPath);		
	}
	
	public void removeSessionFactory(String sessionFactoryId){
		if(!this.sessionFactories.containsKey(sessionFactoryId))
			throw new IllegalArgumentException("Cannot remove SessionFactory, SessionFactory with id ["+sessionFactoryId+"] not registered");
		this.sessionFactories.remove(sessionFactoryId).close();		
	}
	
	public boolean addDataModelClass(String sessionFactoryId, Class<?> dataModelClass){
		SessionFactoryWrapper sessionFactoryWrapper = this.sessionFactories.get(sessionFactoryId);
		if(sessionFactoryWrapper == null){
			sessionFactoryWrapper = new SessionFactoryWrapper(sessionFactoryId);
			this.sessionFactories.put(sessionFactoryId, sessionFactoryWrapper);
		}
		return sessionFactoryWrapper.addDataModelClass(dataModelClass);
	}

	public boolean removeDataModelClass(String sessionFactoryId, Class<?> dataModelClass){
		if(!this.sessionFactories.containsKey(sessionFactoryId))
			throw new IllegalArgumentException("Cannot remove DataModelClass, SessionFactory with id ["+sessionFactoryId+"] not registered");
		return this.sessionFactories.get(sessionFactoryId).removeDataModelClass(dataModelClass);		
	}

	public void close(){
		for (SessionFactoryWrapper sessionFactoryWrapper : this.sessionFactories.values()) {
			sessionFactoryWrapper.close();
		}
		this.sessionFactories.clear();
	}
	
}
